<!-- 票券管理 -->
<template>
  <el-form ref="ruleFormRef" :model="ruleForm" inline class="ruleForm">
    <el-form-item label="请输入电站名称：" prop="stationName">
      <el-input
          v-model="ruleForm.queryRo.stationName"
          style="width: 150px"
          clearable
          placeholder="请输入电站名称"
      />
    </el-form-item>
    <el-form-item label="电站地址：" prop="stationAddress">
      <el-input
          v-model="ruleForm.queryRo.stationAddress"
          style="width: 150px"
          clearable
          placeholder="请输入电站地址"
      />
    </el-form-item>

    <el-form-item label="设备唯一编号：" prop="deviceCode">
      <el-input
          v-model="ruleForm.queryRo.deviceCode"
          style="width: 150px"
          clearable
          placeholder="请输入设备编号"
      />
    </el-form-item>
    <el-form-item label="创建时间：" >
      <el-date-picker
          v-model="createtime"
          type="datetimerange"
          :picker-options="pickerOptions"
          style="width: 400px"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          align="right"
      />
    </el-form-item>
    <el-form-item label="编辑时间：" >
      <el-date-picker
          v-model="updatetime"
          type="datetimerange"
          :picker-options="pickerOptions"
          style="width: 400px"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          align="right"
      />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="search">查 询</el-button>
      <el-button type="success" @click="addStation()">新增</el-button>
    </el-form-item>
  </el-form>

  <el-table :data="tableList" style="width: 100%" v-loading="loading" :show-summary="summary" :summary-method="getSummaries">
    <el-table-column prop="stationName" label="电站名称" align="center" />
    <el-table-column prop="stationAddress" label="电站地址" align="center" />
    <el-table-column prop="deviceCode" label="设备唯一编号" align="center" />
    <el-table-column prop="createTime" label="创建时间" align="center" />
    <el-table-column prop="updateTime" label="编辑时间" align="center" />
    <el-table-column prop="startElectric" label="开始充电电量(kwh)" align="center" />
    <el-table-column prop="picStart" label="开始充电图片" align="center" />

    <el-table-column prop="endElectric" label="结束充电电量(kwh)" align="center" />
    <el-table-column prop="picEnd" label="结束充电图片" align="center" />
    <el-table-column prop="chargeElectric" label="充电量(kwh)" align="center" />

    <el-table-column label="操作" align="center">
      <template #default="scope">
        <el-button link @click="openDialog(scope.row)" type="primary">查看详情</el-button>
        <el-button link type="primary" size="small" @click="editStation(scope.row)">编辑</el-button>
      </template>
    </el-table-column>
  </el-table>
  <footer class="pagination">
    <el-pagination
        v-model:currentPage="ruleForm.current"
        v-model:page-size="ruleForm.pageSize"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        small
    />
  </footer>

  <el-drawer
      v-model="drawer"
      :title="tableFrom.data.id ? '编辑站点充电管理': '新增站点充电管理'"
      :direction="direction">
    <el-form
        ref="ruleFormRef"
        :model="tableFrom.data"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
        :size="formSize"
        status-icon
    >
      <el-form-item label="站点名称" prop="stationName">
                <el-input v-model="tableFrom.data.stationName" placeholder="请填写站点名称" />
<!--        <div class="title">新华之星A站</div>-->
      </el-form-item>
      <el-form-item label="站点地址" prop="stationAddress">
                <el-input v-model="tableFrom.data.stationAddress" placeholder="请填站点地址" />
<!--        <div class="title">三色路</div>-->
      </el-form-item>
      <el-form-item label="设备唯一编号" prop="deviceCode">
        <el-input v-model="tableFrom.data.deviceCode" placeholder="请填设备唯一编号" />
<!--        <div class="title">Epanda001</div>-->
      </el-form-item>
      <el-form-item label="开始充电电量" prop="startElectric">
        (kwh)
        <el-input v-model="tableFrom.data.startElectric"  placeholder="请填开始充电电量(kwh)" />
      </el-form-item>
      <!--      <el-form-item label="开始充电图片" prop="picStart">-->
      <!--        <el-input v-model="tableFrom.data.picStart" placeholder="请填开始充电图片" />-->
      <!--      </el-form-item>-->
      <el-form-item label="开始充电图片" prop="picStart"  style="width: 400px" >
        <!--<el-input type="text" v-model="employee.logo" auto-complete="off" placeholder="请输入logo！"></el-input>-->
        <el-upload
            class="upload-demo"
            action="https://oss-cn-chengdu.aliyuncs.com"
            list-type="picture"
            :before-upload="beforePicUpload"
            :on-success="handlePicSuccess"
            :file-list="fileList"
            :limit="1">
          <el-button size="small" type="primary"  icon="el-icon-picture-outline">上传封面</el-button>
          &nbsp;&nbsp;<span slot="tip" class="el-upload__tip">支持500kb，格式jpg</span>
        </el-upload>
      </el-form-item>
      <el-form-item label="结束充电电量" prop="endElectric">
        (kwh)
        <el-input v-model="tableFrom.data.endElectric" placeholder="请填结束充电电量(kwh)" />
      </el-form-item>
      <el-form-item label="结束充电图片" prop="picEnd"  style="width: 400px" >
        <!--<el-input type="text" v-model="employee.logo" auto-complete="off" placeholder="请输入logo！"></el-input>-->
        <el-upload
            class="upload-demo"
            action="https://oss-cn-chengdu.aliyuncs.com"
            :before-upload="beforePicUpload"
            :on-success="handlePicSuccess"
            list-type="picture"
            :file-list="fileList"
            :limit="1">
          <el-button size="small" type="primary"  icon="el-icon-picture-outline">上传封面</el-button>
          &nbsp;&nbsp;<span slot="tip" class="el-upload__tip">支持500kb，格式jpg</span>
        </el-upload>
      </el-form-item>
      <!--      <el-form-item label="结束充电图片" prop="picEnd">-->
      <!--        <el-input v-model="tableFrom.data.picEnd" placeholder="请填结束充电图片" />-->
      <!--      </el-form-item>-->
      <!--      <el-form-item label="充电量" prop="chargeElectric">-->
      <!--        (kwh)-->
      <!--        <el-input v-model="tableFrom.data.chargeElectric" placeholder="请填充电量(kwh)" />-->
      <!--      </el-form-item>-->

    </el-form>
    <template #footer>
      <div style="flex: auto">
        <!--        <el-button @click="cancelForm">取消</el-button>-->
        <el-button type="primary"  @click="submitForm(ruleFormRef)">确定</el-button>
      </div>
    </template>
  </el-drawer>

  <stationComputeDetailDialog
      v-model:show="showDialog"
      :detail="detail"
  ></stationComputeDetailDialog>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import stationComputeDetailDialog from './components/staionComputeDetailDialog.vue'
import api from '@/api/apis/stationComputeApi'
import {ElMessage, FormInstance, FormRules} from "element-plus";

//==================================================================================================================

// const data = async() => {
//   return {
//     uploadPicData: {},
//   }
var fileList = reactive([
  // {name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'}
])
const handlePicSuccess  = async(res: any, file: { name: any; }) => {
  //上传的完整的文件地址 ： https://oss-cn-chengdu.aliyuncs.com/cc393olajewfjaolfja.jpg
  var urlPath = this.uploadPicData.host + '/' + this.uploadPicData.key.replace("${filename}", file.name);
  this.addForm.pic = urlPath;
  this.$message({message: '上传成功', type: 'success'});
}

const beforePicUpload =  async() =>{
  await getSign(this.uploadPicData);
}

//policy: any; signature: any; ossaccessKeyId: any; dir: any; host: any; key: string;
const getSign = async() => {
  //让这个请求变成同步请求
  api.sign({}).then(res=>{
    console.log('你大爷------',res)
  })
  // await this.$http.get("/oss/sign").then((response: { data: { data: any; }; })=>{
  //   //设置相关的参数
  //   var resultObj = response.data.data;
  //   data.policy = resultObj.policy;
  //   data.signature = resultObj.signature;
  //   data.ossaccessKeyId = resultObj.accessid;
  //   data.dir = resultObj.dir;
  //   data.host = resultObj.host;
  //   //上传的文件名，使用UUID处理一下
  //   data.key = resultObj.dir + '/'+this.getUUID()+'_${filename}';
  // });
}
//==================================================================================================================


const drawer = ref(false)
// const direction = ref('rtl')
// const formSize = ref('default')
// const status = ref(true)
// const sex = ref('男')
const ruleFormRef = ref<FormInstance>()

// 必填规则
const rules = reactive<FormRules>({
    stationName: [
  { required: true, message: '请填站点名称', trigger: 'blur' },
  ],
    stationAddress: [
  { required: true, message: '请填站点地址', trigger: 'blur' },
  ],
    deviceCode: [
  { required: true, message: '请填设备为一遍号', trigger: 'blur' },
  ],
    // { required: true, message: 'Please input Activity name', trigger: 'blur' },
  startElectric: [
    { required: true, message: '请填开始充电电量', trigger: 'blur' },
    // { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
  ],
  // picStart: [
  //   { required: true, message: '请填开始充电图片', trigger: 'blur' },
  // ],
  // password: [
  //     { required: true, message: '请填写员工登录密码', trigger: 'blur' },
  // ],
  endElectric: [
    { required: true, message: '请填结束充电电量', trigger: 'blur' },
  ],
  // picEnd: [
  //   { required: true, message: '请填结束充电图片', trigger: 'blur' },
  // ],
  // chargeElectric: [
  //   { required: true, message: '请填充电量', trigger: 'blur' },
  // ],
  // phone: [
  //   { required: true, message: '请填写员工电话', trigger: 'blur' },
  //   { min: 11, max: 11, message: '请填写正确的电话号码', trigger: 'blur' },
  // ],
})
onMounted(() => {
  getTableList()
  // getRoleAllList()
})

const tableFrom = reactive({
  data:{
    id:"",
    // station_id:"",
    stationName:"",
    stationAddress:"",
    // device_id:"",
    deviceCode:"",
    createTime:"",
    startElectric:"",
    picStart:"",
    updateTime:"",
    endElectric:"",
    picEnd:"",
    chargeElectric:"",

  }
})

var summary = ref(false)
const getSummaries = (param)=>{
  const { columns, data } = param;
  const sums = [];
  columns.forEach((column, index) => {
    const values = data.map(item => {
      // var list = ['startElectric','endElectric','chargeElectric']
      var list = ['chargeElectric']
      if(list.includes(column.property)){
        return Number(item[column.property])
      }
    });

    if (!values.every(value => isNaN(value))) {
      // console.log('值------',values)
      sums[index] = values.reduce((prev, curr) => {
        const value = Number(curr);
        if (!isNaN(value)) {
          return prev + curr;
        } else {
          return prev;
        }
      }, 0);
      sums[index] += ' (kwh)';
    } else {
      sums[index] = '';
    }
  });

  return sums
}
//编辑
const editStation = (row)=>{
  tableFrom.data= {...row}
  // status.value = ruleForm.data.status == 1 ? true : false
  // ruleForm.data.status = 1
  drawer.value = true
  console.log('tableFrom',tableFrom.data)
}

//新增
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      let res, message
      // ruleForm.data.sex = sex.value
      console.log('data',tableFrom.data)
      if(tableFrom.data.id){
        res = await api.updateStation(tableFrom.data)
        message = '编辑成功！'
      }else {
        res = await api.addStation(tableFrom.data)
        message = '新增成功！'
      }
      if(res.data.code == 200){
        ElMessage({
          message: message,
          type: 'success',
        })
        getTableList()
        drawer.value = false
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}


// 新增
const addStation = async (formEl: FormInstance | undefined) => {
  drawer.value = true
  let  obj = {
    // station_id:"",
    stationName:"",
    stationAddress:"",
    // device_id:"",
    deviceCode:"",
    createTime:"",
    startElectric:"",
    picStart:"",
    updateTime:"",
    endElectric:"",
    picEnd:"",
    chargeElectric:"",
  }
  tableFrom.data = obj
}

const ruleForm = reactive({
  queryRo:{
    deviceCode:"",
    stationAddress:"",
    stationName:"",
    createTime:"",
    updateTime:"",
  },
  current: 1,
  pageSize: 50,
  searchCount: true
})
const time=ref<any>([])
//总数
const total = ref(0)
//搜索
const search = () => {
  summary.value = true
  ruleForm.current = 1
  getTableList()
}

//表格数据
const tableList = ref([])
//加载
const loading = ref(false)
onMounted(()=>{
  getTableList()
})

const createtime = ref<any>('')
const updatetime = ref<any>('')

//获取表格数据
const getTableList = async () => {
  loading.value = true
  try {
    let obj = { ...ruleForm }
    // obj.queryRo.startTime =time.value?time.value[0]:undefined
    // obj.queryRo.endTime =time.value?time.value[1]:undefined
    obj.queryRo.createTime =createtime.value?createtime.value:undefined
    obj.queryRo.updateTime =updatetime.value?updatetime.value:undefined
    let {data} = await api.stationComputeListPage(obj)
    tableList.value= data.data.rows
    total.value= Number(data.data.total)

  } catch (error) {
    loading.value = false
  }
  loading.value = false
}
// //改变每页条数
const handleSizeChange = (val: number) => {
  ruleForm.current = 1
  ruleForm.pageSize = val
  getTableList()
}
//改变当前页数
const handleCurrentChange = (val: number) => {
  ruleForm.current = val
  getTableList()
}

//弹框开关
const showDialog = ref(false)
//详情id
const detail = ref()
//打开详情弹框
const openDialog = (val: string) => {
  detail.value = val
  showDialog.value = true
}
</script>

<style scoped lang="scss">
footer {
  display: flex;
  justify-content: center;
  margin-top: 15px;
}
</style>
